<?php

namespace app\admin\controller;

use app\admin\controller\Utils\FileImport;
use app\app\model\ProjectDKModel;
use app\app\model\ProjectModel;
use app\app\model\RandModel;
use app\BaseController;
use PhpOffice\PhpSpreadsheet\Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\ValidateException;
use think\facade\Filesystem;

class ProjectAttendance extends BaseController
{
    /**
     * 导入考勤数据
     * @return void
     * @throws Exception
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function import()
    {
        // 获取表单上传文件
        if (empty(request()->file('file'))) {
            $this->error("请上传文件！");
        }

        try {
            $file = request()->file();
        } catch (\Exception $e) {
            $this->error("文件上传失败");
        }

        try {
            // 验证文件大小，名称等是否正确
            validate([
                'file' => 'filesize:52428800|fileExt:xls,xlsx'
            ])
                ->check($file);
        } catch (ValidateException $e) {
            $this->error($e->getMessage());
        }

        $file_path = root_path('runtime') . 'storage/';
        $file_name = Filesystem::putFile(date('Ymd') . '/' . 'att', $file['file']);

        $data = (new FileImport())
            ->ExcelImport($file_path . $file_name, 0);

        $insert_array = [];
        $error_array = [];
        $i = 0;

        foreach ($data as $k => $v) {
            $i++;

            if ($k == 0) continue;
            if (empty($v[1])) continue;

            $project = ProjectModel::where('project_name', $v[1])
                ->where('is_parent', 1)
                ->find();
            if (empty($project)) {
                $error_array[] = '第' . $i .  '行项目名称异常';
                continue;
            }

            $project_id = $project->id;

            $insert_array[] = [
                'id' => RandModel::randId(),
                'project_id' => $project_id,
                'person_type' => 2,
                'dk_time_in' => FileImport::excelDateParse($v[4]),
                'dk_address' => $v[5] . $v[6] . $v[7] . $v[8],
                'dk_time_out' => null,
                'mark' => '现场履职',
                'user_name' => $v[2] ?: null,
                'user_id' => null,
                'photo_id' => null,
                'create_time' => date('Y-m-d H:i:s'),
            ];
        }

        (!empty($error_array)) && $this->error('上传异常：' . implode('，', $error_array));

        try {
            (new ProjectDKModel())->insertAll($insert_array);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('上传成功');
    }
}